package com.hyc.myvideo.ui.activity.live;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.acmenxd.toaster.Toaster;
import com.anbetter.danmuku.DanMuView;
import com.hyc.myvideo.R;
import com.hyc.myvideo.data.adapter.BouncePlayAdapter;
import com.hyc.myvideo.data.api.model.Bounce;
import com.hyc.myvideo.data.api.model.DanmakuEntity;
import com.hyc.myvideo.data.api.model.Gift;
import com.hyc.myvideo.ui.base.BaseFragment;
import com.hyc.myvideo.utils.DanMuHelper;
import com.hyc.myvideo.utils.imguitl.ImgUitl;
import com.hyc.myvideo.widget.BounceListView;
import com.hyc.utils.StringUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 直播业务界面
 * @author gyb
 * @version 1.0
 * @created 2017/07/27
 */
public class ChatFragment extends BaseFragment {
    @BindView(R.id.player_audio)
    RelativeLayout toolbar;
    private boolean isToolbar = true;
    /**头像背景*/
    @BindView(R.id.player_head_layout)
    LinearLayout  layoutHead;
    /**主播头像*/
    @BindView(R.id.player_img_avatar)
    ImageView imageViewAvatar;
    /**直播/音频*/
    @BindView(R.id.player_b_switch)
    Button buttonSwitch;
    /**关闭*/
    @BindView(R.id.player_b_close)
    Button buttonClose;

    /**直播主题*/
    @BindView(R.id.player_t_theme)
    TextView textViewTheme;
    /**礼物视图*/
    @BindView(R.id.player_gift_view)
    LinearLayout layoutGift;
    /**聊天视图*/
    @BindView(R.id.player_chat_view)
    BounceListView listViewChat;
    /**系统弹幕*/
//    @BindView(R.id.barrage_view)
    private DanMuView danMuView;
    private DanMuHelper danMuHelper;

    /**聊天适配器*/
    private BouncePlayAdapter Adapter;
    private List<Bounce> messageData = new LinkedList<>();

    /**动画*/
    private NumAnim giftNumAnim;
    private TranslateAnimation inAnim;
    private TranslateAnimation outAnim;
    private Timer timer;
    /**礼物视图*/
    private List<View> giftViewCollection = new ArrayList<>();
    private Gift gift= null;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_fragment_chat;
    }
    private Typeface face;
    @Override
    protected void initView() {
        initDanmaku();
        inAnim = (TranslateAnimation) AnimationUtils.loadAnimation(getActivity(), R.anim.gift_in);
        outAnim = (TranslateAnimation) AnimationUtils.loadAnimation(getActivity(), R.anim.gift_out);
        giftNumAnim = new NumAnim();
        clearTiming();
        face = Typeface.createFromAsset(res.getAssets(),"fonts/tintin_talking.ttf");
        textData();
        Adapter =new BouncePlayAdapter(getActivity(), messageData);
        listViewChat.setAdapter(Adapter);
        listViewChat.setSelection(messageData.size());
    }


    private void textData(){
        for(int x=0; x<20; x++){
            messageData.add(new Bounce("昵称昵称","当然上面的第一步是获取你要改变颜色的文字的起始位置到结束位置，接着通过"));
        }
    }




    @Override
    protected void initData(){
        gift =  new Gift("测试发送礼物","http://images.haiwainet.cn/20170718/1500342165930656.jpg");
    }

  @Override protected void onNexts(String result, String method) {

  }

    @Override protected void onError() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
        if (danMuHelper != null) {
            danMuHelper.release();
            danMuHelper = null;
        }
    }

    /***
     * 初始化弹幕
     */
    private void initDanmaku(){
        danMuView = (DanMuView)getActivity().findViewById(R.id.barrage_view);
        danMuHelper = new DanMuHelper(getActivity());
        //初始化弹幕null
        danMuView.prepare();
        danMuHelper.add(danMuView);
    }

    /***
     * 发送一条弹幕
     * @param danmakuEntity
     */
    private void addRoomDanmaku(DanmakuEntity danmakuEntity) {
        if (danMuHelper != null) {
            danMuHelper.addDanMu(danmakuEntity, false);
        }
    }
    
    /**
     * 添加文本弹幕
     * @param islive
     */
    private void addDanmaku(String content,boolean islive) {


    }


    /**
     * 添加礼物view
     */
    private View addGiftView() {
        View view = null;
        if (giftViewCollection.size() <= 0) {
            /*如果垃圾回收中没有view,则生成一个*/
            view = LayoutInflater.from(getActivity()).inflate(R.layout.activity_player_item_gift, null);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.topMargin = 10;
            view.setLayoutParams(lp);
            layoutGift.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
                @Override
                public void onViewAttachedToWindow(View view) { }
                @Override
                public void onViewDetachedFromWindow(View view) {
                    giftViewCollection.add(view);
                }
            });
        } else {
            view = giftViewCollection.get(0);
            giftViewCollection.remove(view);
        }
        return view;
    }

    /**
     * 删除礼物view
     */
    private void removeGiftView(final int index) {
        final View removeView = layoutGift.getChildAt(index);
        outAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) { }
            @Override
            public void onAnimationEnd(Animation animation) {
                layoutGift.removeViewAt(index);
            }
            @Override
            public void onAnimationRepeat(Animation animation) { }
        });
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                removeView.startAnimation(outAnim);
            }
        });
    }

    /****
     * 添加礼物
     * @param gift 礼物实体
     * @param tag  标识符
     */
    private void showGift(Gift gift,String tag) {
        View giftView = layoutGift.findViewWithTag(tag);
        if (giftView == null) {/*该用户不在礼物显示列表*/
            if (layoutGift.getChildCount() > 2) {/*如果正在显示的礼物的个数超过两个，那么就移除最后一次更新时间比较长的*/
                View giftView1 = layoutGift.getChildAt(0);
                ImageView picTv1 = (ImageView) giftView1.findViewById(R.id.player_item_img_gift);
                long lastTime1 = (Long) picTv1.getTag();
                View giftView2 = layoutGift.getChildAt(1);
                ImageView picTv2 = (ImageView) giftView2.findViewById(R.id.player_item_img_gift);
                long lastTime2 = (Long) picTv2.getTag();
                if (lastTime1 > lastTime2) {/*如果第二个View显示的时间比较长*/
                    removeGiftView(1);
                } else {/*如果第一个View显示的时间长*/
                    removeGiftView(0);
                }
            }
            giftView = addGiftView();/*获取礼物的View的布局*/
            giftView.setTag(tag);/*设置view标识*/
            //礼物图标
            ImageView imageView = (ImageView) giftView.findViewById(R.id.player_item_img_gift);
            ImgUitl.setImg(gift.img,imageView,ImgUitl.dip2px(getActivity(),40),ImgUitl.dip2px(getActivity(),40));
            //展示昵称
            TextView nickname = (TextView) giftView.findViewById(R.id.player_item_t_nickname);
            nickname.setText(gift.name);//昵称
            ImageView image= (ImageView) giftView.findViewById(R.id.player_item_img_gift);
            image.setTag(System.currentTimeMillis());/*设置时间标记*/
            final TextView giftNum = (TextView) giftView.findViewById(R.id.player_item_t_num);/*找到数量控件*/
            giftNum.setTypeface(face);
            giftNum.setText("x1");/*设置礼物数量*/
            giftNum.setTag(1);/*给数量控件设置标记*/

            layoutGift.addView(giftView);/*将礼物的View添加到礼物的ViewGroup中*/
            layoutGift.invalidate();/*刷新该view*/
            giftView.startAnimation(inAnim);/*开始执行显示礼物的动画*/
            inAnim.setAnimationListener(new Animation.AnimationListener() {/*显示动画的监听*/
                @Override
                public void onAnimationStart(Animation animation) { }
                @Override
                public void onAnimationEnd(Animation animation) {
                    giftNumAnim.start(giftNum);
                }
                @Override
                public void onAnimationRepeat(Animation animation) { }
            });
        }else{
            ImageView image= (ImageView) giftView.findViewById(R.id.player_item_img_gift);
            TextView giftNum = (TextView) giftView.findViewById(R.id.player_item_t_num);
            giftNum.setTypeface(face);
            int showNum = (Integer) giftNum.getTag() + 1;
            giftNum.setText("x"+showNum);
            giftNum.setTag(showNum);
            image.setTag(System.currentTimeMillis());
            giftNumAnim.start(giftNum);
        }
    }

    /**
     * 定时清除礼物
     */
    private void clearTiming() {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                int count = layoutGift.getChildCount();
                for (int i = 0; i < count; i++) {
                    View view = layoutGift.getChildAt(i);
                    ImageView image= (ImageView) view.findViewById(R.id.player_item_img_gift);
                    long nowtime = System.currentTimeMillis();
                    long upTime = (Long) image.getTag();
                    if ((nowtime - upTime) >= 2000) {
                        removeGiftView(i);
                        return;
                    }
                }
            }
        };
        timer = new Timer();
        timer.schedule(task, 0, 2000);
    }

    /**
     * 发送消息
     */
    private void sendText(Bounce news) {
        if(StringUtils.isEmpty(news.getNews())){
            return;
        }
        messageData.add(news);
        Adapter.updateListView(messageData);
        listViewChat.setSelection(messageData.size());
    }
    /**
     * 数字放大动画
     */
    public class NumAnim {
        private Animator lastAnimator = null;
        public void start(View view) {
            if (lastAnimator != null) {
                lastAnimator.removeAllListeners();
                lastAnimator.end();
                lastAnimator.cancel();
            }
            ObjectAnimator anim1 = ObjectAnimator.ofFloat(view, "scaleX",1.3f, 1.0f);
            ObjectAnimator anim2 = ObjectAnimator.ofFloat(view, "scaleY",1.3f, 1.0f);
            AnimatorSet animSet = new AnimatorSet();
            lastAnimator = animSet;
            animSet.setDuration(200);
            animSet.setInterpolator(new OvershootInterpolator());
            animSet.playTogether(anim1, anim2);
            animSet.start();
        }
    }

    /***
     * 音频/直播切换
     */
    private void showAudio(){
        int bg_round_black30 = R.drawable.bg_round_black30;
        int bg_round_white30 = R.drawable.bg_round_white30;
        int bg_round_white30_1 = R.drawable.bg_round_black30_1;
        if(isToolbar){
            isToolbar =false;
            toolbar.setVisibility(View.VISIBLE);
            buttonClose.setBackgroundResource(bg_round_white30);
            buttonSwitch.setBackgroundResource(bg_round_white30);
            layoutHead.setBackgroundResource(bg_round_white30_1);
            buttonSwitch.setTextColor(getResources().getColor(R.color.color_5));
            buttonClose.setTextColor(getResources().getColor(R.color.color_5));
        }else{
            isToolbar =true;
            toolbar.setVisibility(View.GONE);
            buttonSwitch.setBackgroundResource(bg_round_black30);
            buttonClose.setBackgroundResource(bg_round_black30);
            layoutHead.setBackgroundResource(bg_round_black30);
            buttonSwitch.setTextColor(getResources().getColor(R.color.color_3));
            buttonClose.setTextColor(getResources().getColor(R.color.color_3));
        }
    }



    @OnClick({R.id.player_b_close,R.id.player_b_switch,R.id.player_b_attention,
            R.id.tvChat1,R.id.tvChat2,R.id.tvChat3,R.id.tvChat4,R.id.tvChat5,
    })
    public void onClicks(View view) {
        switch (view.getId()){
            /**关闭直播*/
            case R.id.player_b_close:
                getActivity().finish();
                break;
            /**音频/视频切换*/
            case R.id.player_b_switch:
                showAudio();
                break;
            /**关注*/
            case R.id.player_b_attention:
                Toaster.show("关注");
                break;
            /**测试发送礼物*/
            case R.id.tvChat1:
                DanmakuEntity danmakuEntity = new DanmakuEntity();
                danmakuEntity.setType(DanmakuEntity.DANMAKU_TYPE_USERCHAT);
                danmakuEntity.setName("系统广播");
                danmakuEntity.setAvatar("http://q.qlogo.cn/qqapp/100229475/E573B01150734A02F25D8E9C76AFD138/100");
                danmakuEntity.setLevel(23);
                danmakuEntity.setText("来看美女直播拉!!!!!!!!!");
                addRoomDanmaku(danmakuEntity);

//                showGift(new Gift("测试发送礼物1","http://images.haiwainet.cn/20170718/1500342165930656.jpg"),"1");
                break;
            /**测试发送礼物*/
            case R.id.tvChat2:
                showGift(new Gift("测试发送礼物2","http://images.haiwainet.cn/20170718/1500342165930656.jpg"),"2");
                break;
            /**测试发送礼物*/
            case R.id.tvChat3:
                showGift(new Gift("测试发送礼物3","http://images.haiwainet.cn/20170718/1500342165930656.jpg"),"3");
                break;
            /**测试发送礼物*/
            case R.id.tvChat4:
                showGift(new Gift("测试发送礼物4","http://images.haiwainet.cn/20170718/1500342165930656.jpg"),"4");
                break;
            /**测试发送礼物*/
            case R.id.tvChat5:
                showGift(new Gift("测试发送礼物5","http://images.haiwainet.cn/20170718/1500342165930656.jpg"),"5");
                break;
//            /**测试发送弹幕*/
//            case R.id.tvSendtwo:
//                //addDanmaku("弹幕来了",true);
//                break;

        }
    }
}
